import 'dart:async';

// 当您需要懒惰地生成一系列值时，请考虑使用生成器函数。Dart支持两种生成器功能。
// 源码地址https://github.com/AweiLoveAndroid/Flutter-learning
//***************  这两种写法是一样的,但是第一个写法会简洁很多  ****************//

Iterable<int> genList({int max = 10}) sync* {
  var i = 0;
  while (i < max) {
    yield i;
    i++;
  }
}

Iterable<int> genList2({int max = 10}) {
  var list = <int>[];
  var i = 0;
  while (i < max) {
    list.add(i);
    i++;
  }
  return list.map((i) => i);
}

//***************  async*  ****************//

Stream<int> genStream({int max = 10}) async* {
  int i = 0;
  while (i < max) {
    yield i;
    await Future.delayed(Duration(milliseconds: 300));
    i++;
  }
}

Stream<int> genStream2({int max = 10}) {
  StreamController<int> controller = StreamController();

  Future<void>.delayed(Duration.zero).then((_) async {
    int i = 0;
    while (i < max) {
      controller.add(i);
      await Future.delayed(Duration(milliseconds: 300));
      i++;
    }
    controller.close();
  });

  return controller.stream;
}

main(List<String> args) {
    var aa =genStream();
    aa.listen((event) {
        print(event);
    });
}